<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\AdminUser;
use App\Models\Admin\Goods;
use App\Models\Admin\SalesStrategy;
use App\Models\Admin\Store;
use Illuminate\Support\Facades\Redis;

class SalesController extends BaseController
{

    /**
     * 金额满赠列表
     */
    public function amountStrategyList()
    {
        $list = $this->salesStrategyList(1);

        return view('admin/sales/amountStrategyList', ['data' => $list]);
    }

    /**
     * 单品满赠列表
     */
    public function itemStrategyList()
    {
        $list = $this->salesStrategyList(2);

        return view('admin/sales/itemStrategyList', ['data' => $list]);
    }

    /**
     * 获取销售策略列表数据
     * @param $type
     * @return mixed
     */
    public function salesStrategyList($type)
    {
        $where['type'] = $type;
        $where['start'] = $this->requestArr['start'];
        $where['end'] = $this->requestArr['end'];

        $list = SalesStrategy::getList($where);
        foreach ($list as &$value) {
            $value['type_str'] = $value['type'] == 1 ? '金额满赠' : '单品满赠';
            $value['status'] = $value['end'] > time() ? '正常' : '已失效';
            $value['start'] = date("Y-m-d H:i:s", $value['start']);
            $value['end'] = date("Y-m-d H:i:s", $value['end']);
            if ($value['type'] == 2) {
                $info = Goods::getInfo(['id' => $value['goods_id']]);
            }
            $value['note'] = $value['type'] == 1 ? '金额满' . $value['amount'] . '元' : '单品【' . $info['goods_name'] . '】满' . $value['goods_number'] . '件';
        }
        if (!empty($where['start'])) {
            $list->appends(['start' => $where['start']])->render();
        }
        if (!empty($where['end'])) {
            $list->appends(['end' => $where['end']])->render();
        }

        return $list;
    }

    /**
     * ajax获取策略详情
     */
    public function ajaxGetStrategyInfo()
    {
        $id = $this->requestArr['id'];
        if ($id) {
            $info = SalesStrategy::getInfo(['id' => $id]);
            $info['send_goods'] = json_decode($info['send_goods'], true);
            $sendGoods = [];
            $goods = Goods::getAll();
            foreach ($goods as $kk => $vv) {
                if ($vv['goods_sale_num'] == null) {
                    $goods[$kk]['goods_sale_num'] = 0;
                }
            }
            $list = $goods;
            foreach ($goods as $key => &$val) {
                foreach ($info['send_goods'] as $v) {
                    if ($v['id'] == $val['id']) {
                        unset($goods[$key]);
                        $tmp = $val;
                        $tmp['number'] = $v['number'];
                        $sendGoods[] = $tmp;
                    }
                }
            }
            $data = ['list' => $list, 'left' => array_values($goods), 'right' => $sendGoods];
        } else {
            $goods = Goods::getAll();
            foreach ($goods as $key => &$val) {
                if ($val['goods_sale_num'] == null) {
                    $val['goods_sale_num'] = 0;
                }
            }
            $data = ['list' => $goods];
        }

        successMsg($data);
    }

    /**
     * 添加销售策略
     */
    public function salesStrategyAdd()
    {
        $post = $this->requestArr;
        $type = $post['type'];
        if ($this->requestMethod == 'POST') {
            unset($post['goods']);
            $post['start'] = strtotime($post['start']);
            $post['end'] = strtotime($post['end']);
            $post['send_goods'] = json_encode($post['send_goods']);
            if ($type == 2) {
                $info = Goods::getInfo(['goods_sn' => $post['goods_sn']]);
                if (!$info) {
                    errorMsg('未找到商品：' . $post['goods_sn']);
                }
                $post['goods_id'] = $info['id'];
                unset($post['goods_sn']);
            };
            unset($post['right-number']);
            $post['updated_user'] = $this->userArr['user_name'];
            $post['created_user'] = $this->userArr['user_name'];
            $result = SalesStrategy::add($post);
            if ($result) {
                successMsg();
            }
            errorMsg('添加失败，请稍后重试');
        }
        $goods = Goods::getAll();
        foreach ($goods as &$val) {
            if ($val['goods_sale_num'] == null) {
                $val['goods_sale_num'] = 0;
            }
        }

        if ($type == 1) {
            // 金额满赠策略
            return view('admin/sales/amountStrategyAdd', ['goods' => $goods]);
        } else {
            // 单品满赠策略
            return view('admin/sales/itemStrategyAdd', ['goods' => $goods]);
        }
    }

    /**
     * 编辑销售策略
     */
    public function salesStrategyEdit()
    {
        $post = $this->requestArr;
        $id = $post['id'];
        $info = SalesStrategy::getInfo(['id' => $id]);
        if ($this->requestMethod == 'POST') {
            $post['start'] = strtotime($post['start']);
            $post['end'] = strtotime($post['end']);
            $post['send_goods'] = json_encode($post['send_goods']);
            if ($info['type'] == 2) {
                $goodsInfo = Goods::getInfo(['goods_sn' => $post['goods_sn']]);
                if (!$goodsInfo) {
                    errorMsg('未找到商品：' . $post['goods_sn']);
                }
                $post['goods_id'] = $goodsInfo['id'];
                unset($post['goods_sn']);
            }
            unset($post['right-number']);
            $post['updated_user'] = $this->userArr['user_name'];
            $result = SalesStrategy::edit($id, $post);
            if ($result) {
                successMsg();
            }
            errorMsg('添加失败，请稍后重试');
        }

        $info['start'] = date('Y-m-d H:i:s', $info['start']);
        $info['end'] = date('Y-m-d H:i:s', $info['end']);
        $info['send_goods'] = json_decode($info['send_goods'], true);
        if ($info['type'] == 2) {
            $goodsInfo = Goods::getInfo(['id' => $info['goods_id']]);
            $info['goods_sn'] = $goodsInfo['goods_sn'];
            $info['goods_name'] = $goodsInfo['goods_name'];
            $info['goods_price'] = $goodsInfo['goods_price'];
        }

        $send = [];
        $all  = Goods::getAll();
        $list = $all;
        foreach ($list as $key => &$val) {
            if ($val['goods_sale_num'] == null) {
                $val['goods_sale_num'] = 0;
            }
            foreach ($info['send_goods'] as $v) {
                if ($v['id'] == $val['id']) {
                    unset($list[$key]);
                    $tmp = $val;
                    $tmp['number'] = $v['number'];
                    $send[] = $tmp;
                }
            }
        }

        if ($info['type'] == 1) {
            // 金额满赠策略
            return view('admin/sales/amountStrategyEdit', ['info' => $info, 'list' => $list, 'send' => $send]);
        } else {
            // 单品满赠策略
            return view('admin/sales/itemStrategyEdit', ['info' => $info, 'list' => $all, 'left' => $list, 'send' => $send]);
        }
    }

    /**
     * 删除销售策略
     */
    public function salesStrategyDel()
    {
        $id = $this->requestArr['id'];

        $result = SalesStrategy::del($id);
        if ($result) {
            successMsg();
        }
        errorMsg('删除失败，请稍后重试');
    }

    /**
     * 组合商品列表
     */
    public function multipleGoodsList()
    {
        $where['is_group'] = 1;
        $where['goods_name'] = $this->requestArr['goods_name'];

        $list = Goods::getList($where);
        
        // 添加调试信息
        \Log::info('Multiple Goods List Query:', [
            'where' => $where,
            'count' => $list->count(),
            'first_item' => $list->first()
        ]);
        
        if (!empty($where['goods_name'])) {
            $list->appends(['goods_name' => $where['goods_name']])->render();
        }
        return view('admin/sales/multipleGoodsList', ['data' => $list]);
    }

    /**
     * 组合商品列表
     */
    public function multipleGoodsListDel()
    {
        $id = $this->requestArr['id'];
        if ($id) {
            Goods::where('id', $id)->delete();
            successMsg();
        }
        errorMsg();
    }

    /**
     * 特价（促销）商品列表
     */
    public function promotionGoodsList()
    {
        $where['is_group'] = 0;
        $where['promotion'] = 1;
        $where['goods_name'] = $this->requestArr['goods_name'];

        $list = Goods::getList($where);
        if (!empty($where['goods_name'])) {
            $list->appends(['goods_name' => $where['goods_name']])->render();
        }

        return view('admin/sales/promotionGoodsList', ['data' => $list]);
    }

    /**
     * 默认策略列表
     */
    public function defaultStrategyList()
    {
        $key = 'DEFAULT:STRATEGY';
        $json = Redis::GET($key);

        $data = array();
        if ($json) {
            $data = json_decode($json, true);
            $data['send_goods'] = json_decode($data['send_goods'], true);

            $goodsIds = array_column($data['send_goods'], 'id');
            $goods = Goods::whereIn('id', $goodsIds)->select('id', 'goods_name')->get()->toArray();

            foreach ($data['send_goods'] as &$val) {
                foreach ($goods as $v) {
                    if ($v['id'] == $val['id']) {
                        $val['goods_name'] = $v['goods_name'];
                    }
                }
            }
        }

        return view('admin/sales/defaultStrategyList', ['data' => $data]);
    }

    /**
     * 添加基础策略
     */
    public function defaultStrategyAdd()
    {
        $post = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            unset($post['right-number']);
            $post['send_goods'] = json_encode($post['send_goods']);

            $key = 'DEFAULT:STRATEGY';
            Redis::SET($key, json_encode($post, JSON_UNESCAPED_UNICODE));

            successMsg();
        }
        $goods = Goods::getAll();
        foreach ($goods as &$val) {
            if ($val['goods_sale_num'] == null) {
                $val['goods_sale_num'] = 0;
            }
        }

        return view('admin/sales/defaultStrategyAdd', ['goods' => $goods]);
    }

    /**
     * 编辑默认策略
     */
    public function defaultStrategyEdit()
    {
        $post = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            unset($post['right-number']);
            $post['send_goods'] = json_encode($post['send_goods']);

            $key = 'DEFAULT:STRATEGY';
            Redis::SET($key, json_encode($post, JSON_UNESCAPED_UNICODE));

            successMsg();
        }
        $key = 'DEFAULT:STRATEGY';
        $json = Redis::GET($key);
        $data = json_decode($json, true);
        $data['send_goods'] = json_decode($data['send_goods'], true);

        $send = [];
        $goods = Goods::getAll();
        foreach ($goods as $key => &$val) {
            if ($val['goods_sale_num'] == null) {
                $val['goods_sale_num'] = 0;
            }
            foreach ($data['send_goods'] as $v) {
                if ($v['id'] == $val['id']) {
                    unset($goods[$key]);
                    $tmp = $val;
                    $tmp['number'] = $v['number'];
                    $send[] = $tmp;
                }
            }
        }

        return view('admin/sales/defaultStrategyEdit', ['data' => $data, 'goods' => $goods, 'send' => $send]);
    }

    /**
     * ajax获取默认策略详情
     */
    public function ajaxGetDefaultStrategyInfo()
    {
        $key = 'DEFAULT:STRATEGY';
        $json = Redis::GET($key);
        if ($json) {
            $data = json_decode($json, true);
            $data['send_goods'] = json_decode($data['send_goods'], true);
            $goodsIds = array_column($data['send_goods'], 'id');

            $sendGoods = array();
            $goods = Goods::getAll();
            foreach ($goods as $kk => $vv) {
                if ($vv['goods_sale_num'] == null) {
                    $goods[$kk]['goods_sale_num'] = 0;
                }
            }
            $list = $goods;
            foreach ($goods as $key => &$val) {
                foreach ($data['send_goods'] as $v) {
                    if ($v['id'] == $val['id']) {
                        unset($goods[$key]);
                        $tmp = $val;
                        $tmp['number'] = $v['number'];
                        $sendGoods[] = $tmp;
                    }
                }
            }
            $data = ['list' => $list, 'left' => array_values($goods), 'right' => $sendGoods];
        } else {
            $goods = Goods::getAll();
            foreach ($goods as $key => &$val) {
                if ($val['goods_sale_num'] == null) {
                    $val['goods_sale_num'] = 0;
                }
            }
            $data = ['list' => $goods];
        }

        successMsg($data);
    }

    /**
     * 删除默认策略
     */
    public function defaultStrategyDel()
    {
        $key = 'DEFAULT:STRATEGY';
        Redis::DEL($key);

        successMsg();
    }
}
